package inglar.autotc.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

/**
 * Class for handling configuration files
 * @author Lee
 */
public class ConfigFile {
	
	private HashMap<String, String> data = null;
	private String configfile = null;

	private ConfigFile() {
		data = new HashMap<String, String>(32);
	}
	
	public ConfigFile(String filename) {
		this();
		
		File file = new File(filename);
		if(file.exists() && file.canRead()) {
			configfile = filename;
			getKeys(file);
		} 
	}
	
	private void getKeys(File file) {
		try {
			Scanner scan = new Scanner(file);
			scan.reset();
			while(scan.hasNextLine()) {
				String temp = scan.nextLine().trim();
				if(temp.startsWith("#")) continue; // found comment
				
				// find delimiters
				int pos_hash = temp.indexOf("#");
				int pos_equ = temp.indexOf("=");
				if(pos_equ < 0) continue; // key without '=', invalid occurrence
				
				// get value
				String value;
				if(pos_hash < 0) { // no comment part
					value = temp.substring(pos_equ + 1).trim();
				} else {
					value = temp.substring(pos_equ + 1, pos_hash);
				}
				
				// get key
				String key = temp.substring(0, pos_equ).trim();
				
				// put key-value pair to list
				data.put(key, value);
			}
		} catch (FileNotFoundException e) {
			
		}
	}
	
	/**
	 * Gets a value from this {@link ConfigFile}.
	 * @param key the key
	 * @return a {@link String} containing the mapped value to the parameter key
	 */
	public String getValue(String key, String defaultValue) {
		String retval = data.get(key);
		if(retval == null) return defaultValue;
		return retval;
	}
	
	/**
	 * Prints known key-value pairs into the standard output stream.
	 * @deprecated This functions prints to {@code stdout}.
	 */
	public void dumpdata() {
		System.out.println("configfile: " + configfile);
		System.out.println(data);
	}
	
}
